<template>
  <a-modal
    v-model="importVisible"
    title="导入车辆"
    width="1000px"
    dialogClass="createFormStyle"
    :bodyStyle="{ height: '500px', overflowY: 'auto' }"
  >
    <template slot="footer">
      <a-button @click="importVisible = false" type="primary">{{ $t('back') }}</a-button>
    </template>
    <div>
      <a-input
        class="formFileInput"
        :placeholder="$t('formatFiles')"
        readOnly
        :value="importFile"
        style="width:400px;margin-right: 10px"
      >
        <template #addonAfter>
          <i class="iconfont icon-shangchuan" @click="$refs.upload.uploadDo()"></i>
        </template>
      </a-input>
      <a-button
        @click="downloadTemplate"
        :loading="downloading"
      >{{ $t('downloadTemplate') }}</a-button>
      <a-spin :spinning="importing" tip="导入中...">
        <div style="min-height: 300px">
          <template v-if="uploadRes.fail.length > 0">
            <h4 style="margin-top:20px;color:red">失败明细(共{{uploadRes.failCount}}条)：</h4>
            <a-table
              ref="importFailTable"
              class="h100 withMinHeightTbodyBox"
              :rowKey="(record, index) => 'fail-' + index"
              :columns="importFailColumns"
              :data-source="uploadRes.fail"
              :scroll="{x:1500,y:300}"
              :pagination="false"
            >
  <!--            <template slot-scope="text,record" slot="company">-->
  <!--              <table-ellipsis :text="$store.getters.getDictCodeObj('companyDictCode')[record.model.company]" key="t-company"></table-ellipsis>-->
  <!--            </template>-->
  <!--            <template slot-scope="text,record" slot="power">-->
  <!--              <table-ellipsis :text="$store.getters.getDictCodeObj('powerTypeDictCode')[record.model.power]" key="t-power"></table-ellipsis>-->
  <!--            </template>-->
  <!--            <template slot-scope="text,record" slot="saleArea">-->
  <!--              <table-ellipsis :text="$store.getters.getDictCodeObj('saleAreaDictCode')[record.model.saleArea]" key="t-saleArea"></table-ellipsis>-->
  <!--            </template>-->
              <span slot="message" slot-scope="message" style="color:red;white-space: pre-line">
                  {{ message }}
              </span>
            </a-table>
          </template>
          <template v-if="uploadRes.success.length > 0">
            <h4 style="margin-top:20px;">导入成功(共{{uploadRes.successCount}}条)：</h4>
            <a-table v-if="uploadRes.success.length > 0"
                     ref="importSuccessTable"
                     class="h100 withMinHeightTbodyBox"
                     :rowKey="(record, index) => 'suc-' + index"
                     :columns="importSuccessColumns"
                     :data-source="uploadRes.success"
                     :scroll="{x:1500,y:300}"
                     :pagination="false"
            >
            </a-table>
          </template>
        </div>
      </a-spin>
      <!-- 来自文件上传 -->
      <local-upload
        ref="upload"
        :domView="false"
        @showFileObj="showFileObj"
        :accept="['.xls','.xlsx']"
      ></local-upload>
    </div>
  </a-modal>
</template>
<script>
import { downloadBlobFile } from '@/utils/functions'
import LocalUpload from '@/components/Upload/LocalUpload'

export default {
  components: {
    LocalUpload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    cols: {
      type: Array,
      default: []
    },
  },
  computed: {
    importVisible:{
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('change', val);    // 触发
        // this.changeOption(val)
      }
    }
  },
  data () {
    var data = {
      importFile:'',
      uploadRes:{
        fail: [],
        success: [],
        failCount: 0,
        successCount: 0,
      },
      importing: false,
      exporting: false,
      downloading: false,
    }
    data.importFailColumns = [...this.cols, {
      title: '失败原因',
      dataIndex: 'message',
      width: 200,
      fixed: 'right',
      scopedSlots: { customRender: 'message' }
    }]
    data.importSuccessColumns = [...this.cols]
    return data
  },
  model: {
    prop: "visible", //绑定的值，通过父组件传递
    event: "change" //自定义事件名
  },
  created () {

  },
  watch: {
    visible (val) {
      if (!val) {
        this.importFile = '';
        this.uploadRes.fail=[];
        this.uploadRes.success=[];
      }
    }
  },
  methods: {
    downloadTemplate() {
      this.downloading = true
      this.$store.dispatch('downloadVehicleExcelTpl').then((res) => {
        downloadBlobFile(res, '车辆导入模板.xlsx')
      }).finally(() => {
        this.downloading = false
      })
    },
    showFileObj (value) {
      const vm = this
      vm.importFile = value.name
      const formData = new FormData()
      formData.append('file', value)
      // formData.append('vehicleType', this.vehicleType)
      this.uploadRes.fail = [];
      this.uploadRes.failCount = 0;
      this.uploadRes.success = [];
      this.uploadRes.successCount = 0;
      this.importing = true;
      vm.$api.uploadVehicleExcel(formData).then(res => {
        if (res.data) {
          if(res.data.fail){
            res.data.fail.forEach((item) => {
              vm.uploadRes.fail.push({
                ...item.data,
                message : item.message,
              });
            })
            vm.uploadRes.failCount = vm.uploadRes.fail.length;
            // 截取500条 TODO 前端分页、导出
            vm.uploadRes.fail.splice(500);
          }
          if(res.data.success){
            res.data.success.forEach((item) => {
              vm.uploadRes.success.push(item.data);
            })
            vm.uploadRes.successCount = vm.uploadRes.success.length;
            vm.uploadRes.success.splice(500);
          }
          if (vm.uploadRes.successCount === 0 && vm.uploadRes.failCount === 0) {
            vm.$message.error("没有数据！");
          }
          if (vm.uploadRes.successCount > 0) {
            this.refreshData(false);
          }
        }
      }).catch(() => {
        vm.importFile = ''
      }).finally(() => {
        this.importing = false;
      })
    },
  }
}
</script>
<style lang="less">
.importCarForm {
  .ant-form-item {
    margin-bottom: 0;
  }
  .importCarBtn {
    width: 100%;
  }
}
</style>
<style scoped lang="less">
.uploadResultCol {
  margin-top: 15px;
  span {
    margin-right: 15px;
  }
  .uploadResultTitle {
    font-size: 14px;
    font-weight: bold;
  }
}
</style>
